<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2021/10/13
 * Time: 11:27
 * Desc: 新闻
 */
declare (strict_types=1);

namespace app\api\controller;

use app\api\base\controller\Base;

class News extends Base
{
    /**
     * 新闻列表
     */
    public function getAll(){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"http://np-listapi.eastmoney.com/comm/web/getNewsByColumns?client=web&biz=web_news_col&column=344&order=1&needInteractData=0&page_index=1&page_size=5&req_trace=1685090074042&fields=code,showTime,title,mediaName,summary,image,url,uniqueUrl,Np_dst&types=1,20&callback=jQuery183046537248057516_1685090073591&_=1685090074042");
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        $output = curl_exec($ch);
        curl_close($ch);
        $result = [];
        preg_match_all("/(?:\()(.*)(?:\))/i",$output, $result);
        $ret = json_decode($result[1][0],true);

        $newArr = [];
        foreach ($ret['data']['list'] as $val){
            $tmpArr = [
                'showTime' => isset($val['showTime']) && $val['showTime'] != '' ? $val['showTime'] : '',
                'summary' => isset($val['summary']) && $val['summary'] != '' ? $val['summary'] : '',
                'mediaName' => isset($val['mediaName']) && $val['mediaName'] != '' ? $val['mediaName'] : '',
                'image' => '',
                'base64Image' => ''
            ];

            if(isset($val['image'])){
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $val['image']);              // 设置请求的 URL
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);      // 返回响应数据而不是直接输出
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);      // 跟踪重定向
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0'); // 模拟浏览器
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);      // 禁用 SSL 验证 (如果是 HTTPS 请求时需要)
                $response = curl_exec($ch);  // 执行请求并获取响应
                if(curl_errno($ch)) {
                    echo 'cURL error: ' . curl_error($ch);  // 错误处理
                }
                curl_close($ch);
                $base64Image = base64_encode($response);
                $tmpArr['base64Image'] = 'data:image/jpeg;base64,'.$base64Image;
                $tmpArr['image'] = $val['image'];
            }
            $url = str_replace('http://finance.eastmoney.com/a/','',$val['uniqueUrl']);

            $tmpArr['url'] = str_replace('.html','',$url);

            $newArr[] = $tmpArr;
        }

        return json(_S('获取成功',$newArr));
    }

    public function getDetail(){
        $id = input('id','');
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://dm.gailzx17.com/index/api/xq?id=".$id);
        curl_setopt($ch,CURLOPT_URL,"https://newsinfo.eastmoney.com/kuaixun/v2/api/content/getnews?newsid={$id}&newstype=1&guid=appzxzw8e989870-c9c0-9544-7585-329f046273c2&source=wap&version=1&language=&pkg=");
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        //curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch,CURLOPT_HEADER,0);
        $output = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($output,true);

        $info = [
            'title' => '',
            'content' => ''
        ];

        if(!empty($result) && isset($result['news']) && !empty($result['news'])){
            //判断是否有图片
            if(isset($result['news']['images']) && !empty($result['news']['images'])){

                foreach($result['news']['images'] as $imageVal){
                    $url = $imageVal['src'];

                    // 初始化 cURL 会话
                    $ch = curl_init();

                    // 设置 cURL 选项
                    curl_setopt($ch, CURLOPT_URL, $url);              // 设置请求的 URL
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);      // 返回响应数据而不是直接输出
                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);      // 跟踪重定向
                    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0'); // 模拟浏览器
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);      // 禁用 SSL 验证 (如果是 HTTPS 请求时需要)

                    $response = curl_exec($ch);  // 执行请求并获取响应

                    if(curl_errno($ch)) {
                        echo 'cURL error: ' . curl_error($ch);  // 错误处理
                    }

                    curl_close($ch);

                    $base64Image = base64_encode($response);

                    $style = isset($imageVal['style']) ? $imageVal['style'] : '';

                    $result['news']['body'] = str_replace($imageVal['label'],'<img src="data:image/jpeg;base64,'.$base64Image.'" style="'.$style.' width:100%">',$result['news']['body']);
                }

            }

            $cleaned = preg_replace('/<a[^>]*>(.*?)<\/a>/is', '', $result['news']['body']);

            $info['title'] = $result['news']['description'];
            $info['content'] = $cleaned;
        }
        return json(_S('获取成功',$info));
    }
}
